package cn.dslcode.security.config.filter;

import cn.dslcode.common.core.string.StringUtil;
import cn.dslcode.security.common.CaptchaAuthenticationException;
import cn.dslcode.security.common.DataCenter;
import cn.dslcode.security.config.handler.CustomAuthenticationFailureHandler;
import cn.dslcode.security.config.handler.CustomAuthenticationSuccessHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dongsilin
 * @version 2018/4/8.
 *          图片验证码Filter
 */
@Slf4j
@Component
public final class CustomCaptchaVerifyFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CustomAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private CustomAuthenticationSuccessHandler authenticationSuccessHandler;


    @PostConstruct
    public void init() {
        AntPathRequestMatcher requestMatcher = new AntPathRequestMatcher(DataCenter.loginFormUri, RequestMethod.POST.name());
        setRequiresAuthenticationRequestMatcher(requestMatcher);
        setAuthenticationManager(authenticationManager);
        setAuthenticationSuccessHandler(authenticationSuccessHandler);
        setAuthenticationFailureHandler(authenticationFailureHandler);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String captchaCode = request.getParameter("captchaCode");
        if (StringUtil.isEmpty(captchaCode)) {
            throw new CaptchaAuthenticationException("验证码不能为空");
        }
        if (StringUtil.ne(captchaCode, "1234")) {
            throw new CaptchaAuthenticationException("验证码错误");
        }
        return super.attemptAuthentication(request, response);
    }

}